﻿using System;
using System.Collections.Generic;
using System.IO;

using System.Net;
using System.Text;

namespace LaKaLaPay
{
    public static class HttpUtil
    {
        /// <summary>
        /// 发送JSON POST模式。
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postStr"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static string HttpReqJson(string url, string postStr, int timeOut)
        {
            //当 httpwebrequest.method是，POST时，，一定要加上。。。hwr.ServicePoint.Expect100Continue = false; 否则，当有网络错误/换IP时，就会把线程卡住
            //https://blog.csdn.net/superhoy/article/details/18598835

            HttpWebRequest req = null;
            HttpWebResponse rsp = null;
            try
            {
                #region http web request

                byte[] data = Encoding.UTF8.GetBytes(postStr);
                req = (HttpWebRequest)WebRequest.Create(url);
                req.Timeout = timeOut * 1000;
                req.ReadWriteTimeout = timeOut * 1000;
                req.Method = "POST";
                req.KeepAlive = false;
                req.ContentType = "application/json;charset=utf-8";

                req.ServicePoint.Expect100Continue = false;//2018-8-8

                req.ContentLength = data.Length;
                using (Stream putStream = req.GetRequestStream())
                {
                    putStream.Write(data, 0, data.Length);
                }

                rsp = req.GetResponse() as HttpWebResponse;
                byte[] by = new byte[800];
                using (Stream stream = rsp.GetResponseStream())
                {
                    int size = 1024;
                    int read = 0;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] buffer = new byte[size];
                        do
                        {
                            read = stream.Read(buffer, 0, size);
                            ms.Write(buffer, 0, read);
                        } while (read > 0);

                        by = ms.ToArray();
                    }
                }


                string strRst = Encoding.UTF8.GetString(by);
                #endregion

                return strRst;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (rsp != null) rsp.Close();
                if (req != null) req.Abort();//2018-7-31，增加
            }

        }

        public static string HttpPostJson(string url, string body, IDictionary<string, string> header, int timeOut, IDictionary<string, string> rspHeader)
        {
            string rst = "";
            Encoding enc1 = Encoding.UTF8;
            byte[] content = enc1.GetBytes(body);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            request.Timeout = timeOut * 1000;
            request.ReadWriteTimeout = timeOut * 1000;
            request.KeepAlive = false;
            request.ServicePoint.Expect100Continue = false;
            request.ContentLength = content.Length;
            //设置请求header
            foreach (var item in header)
            {
                request.Headers.Add(item.Key, item.Value);
            }

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(content, 0, content.Length);
            }

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, enc1);
                rst = reader.ReadToEnd();
            }

            //收集响应header
            if (rspHeader == null)
            {
                rspHeader = new Dictionary<string, string>();
            }
            foreach (var item in response.Headers.AllKeys)
            {
                rspHeader.Add(item, response.Headers[item]);
            }

            if (response != null)
            {
                response.Close();
                response = null;
            }
            if (request != null)
            {
                request.Abort();//2018-7-31，增加
                request = null;
            }

            return rst;
        }


        public static string HttpReqXml(string url, string content, int timeOut)
        {

            HttpWebRequest req = null;
            HttpWebResponse res = null;

            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(content);

                req = (HttpWebRequest)WebRequest.Create(url);
                req.Timeout = timeOut * 1000;
                req.ReadWriteTimeout = timeOut * 1000;
                req.Method = "POST";
                req.KeepAlive = false;

                req.ContentLength = bytes.Length;
                using (Stream putStream = req.GetRequestStream())
                {
                    putStream.Write(bytes, 0, bytes.Length);
                }

                res = req.GetResponse() as HttpWebResponse;
                string strreturn = string.Empty;
                using (Stream stream = res.GetResponseStream())
                {
                    StreamReader sr = new StreamReader(stream);
                    strreturn = sr.ReadToEnd().ToString();
                }

                return strreturn;

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (res != null) res.Close();
                if (req != null) req.Abort();
            }
        }


        public static string HttpPostJson(string url, string body, IDictionary<string, string> header, int timeOut)
        {
            string rst = "";
            Encoding enc1 = Encoding.UTF8;
            byte[] content = enc1.GetBytes(body);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            request.Timeout = timeOut * 1000;
            request.ReadWriteTimeout = timeOut * 1000;
            request.KeepAlive = false;
            request.ServicePoint.Expect100Continue = false;
            request.ContentLength = content.Length;
            //设置请求header
            foreach (var item in header)
            {
                request.Headers.Add(item.Key, item.Value);
            }

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(content, 0, content.Length);
            }

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, enc1);
                rst = reader.ReadToEnd();
            }



            if (response != null)
            {
                response.Close();
                response = null;
            }
            if (request != null)
            {
                request.Abort();//2018-7-31，增加
                request = null;
            }

            return rst;
        }

    }
}
